package com.example.test;

import java.io.*;

public class Main {

    private static String file = "D:\\Serializable";

    private static void writeUser() {

        User user = new User();
        user.setId(10);
        user.setName("Jerry");
        user.setAge(20);

        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(new File(file)));
            outputStream.writeObject(user);
            outputStream.close();

            System.out.println("Serializable success");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error writeUser: " + e);
        }
    }

    private static void readUser() {
        User user = null;

        try {
            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(new File(file)));

            user = (User) inputStream.readObject();

            System.out.println("Deserializable success");

            System.out.println("User ID: " + user.getId() + "\nUser Name: " + user.getName() + "\nUser Age: " + user.getAge());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("Error readUser: " + e);
        }
    }

    public static void main(String[] args) {
        writeUser();
        readUser();
    }

}
